import sys
from pathlib import Path

from PySide6.QtGui import QResizeEvent, Qt
from PySide6.QtCore import Signal
from PySide6.QtWidgets import *
from view.base import TableFrameBase
from components import OpenFileDialog
from pandas import read_excel
from tools import ExcelRead
from qfluentwidgets import ComboBox, StateToolTip, InfoBar, TransparentToolButton, FluentIcon
from common import UnionQueryThread


class UnionQueryView(QFrame):
    returned = Signal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.initUI()
        self.initLayout()
        self.initEvent()

    def initUI(self):
        self.returnButton = TransparentToolButton()
        self.returnButton.setFixedSize(40, 40)
        self.returnButton.setIcon(FluentIcon.RETURN)

        self.tableFrame = TableFrameBase()
        self.tableFrame.setHeaders(['文件名', '完整路径', '联合查询键', 'sheet页'])
        self.tableFrame.setTitle('Excel联合查询')

        self.stateToolTip = StateToolTip('Excel联合查询', '正在根据键合并excel表，请稍后。。。', self)
        self.stateToolTip.hide()

        self.unionThread = UnionQueryThread(self)

    def initLayout(self):
        self.vBox = QVBoxLayout(self)
        self.vBox.setContentsMargins(0, 0, 0, 0)
        self.vBox.setSpacing(10)

        self.vBox.addWidget(self.returnButton, 0, Qt.AlignmentFlag.AlignLeft)
        self.vBox.addWidget(self.tableFrame)

    def initEvent(self):

        def return_event():
            self.tableFrame.clear()
            self.returned.emit()

        self.returnButton.clicked.connect(return_event)

        self.tableFrame.added.connect(self.add_event)
        self.tableFrame.saved.connect(self.save_event)
        self.tableFrame.started.connect(self.started_event)

        self.unionThread.started.connect(self.started_thread)
        self.unionThread.error.connect(lambda msg: InfoBar.error('错误', content=msg, duration=5000, parent=self))
        self.unionThread.finished.connect(self.finished_thread)

    def add_event(self):
        files = OpenFileDialog(self).getOpenFileNames(filter='Excel文件(*.xlsx)')[0]
        for index, file in enumerate(files):
            fp = Path(file)
            e_read = ExcelRead(file)
            self.tableFrame.addItem([fp.name, file, '', ''])
            columns = list(read_excel(file).columns)
            columnsComBox = ComboBox()
            columnsComBox.setFixedHeight(30)
            columnsComBox.addItems(columns)
            sheetComBox = ComboBox()
            sheetComBox.setFixedHeight(30)
            sheetComBox.addItems(e_read.sheets())
            self.tableFrame.setCellWidget(index, 2, columnsComBox)
            self.tableFrame.setCellWidget(index, 3, sheetComBox)

    def save_event(self):
        file = OpenFileDialog(self).getSaveFileName(_dir='./UnionQuery.xlsx', filter='Excel文件(*.xlsx)')[0]
        self.tableFrame.setLineText(file)

    def started_event(self):
        col1 = self.tableFrame.getColumnValues(1)
        col2 = self.tableFrame.getColumnWidgetText(2)
        col3 = self.tableFrame.getColumnWidgetText(3)
        save_path = self.tableFrame.lineText()
        data = []
        for i, v in enumerate(col2):
            data.append({'key': v, 'sheet_name': col3[i], 'file': col1[i]})
        if len(data) == 0 or save_path is False:
            return

        self.unionThread.set_value(data, save_path)
        self.unionThread.start()

    def started_thread(self):
        self.stateToolTip.show()

    def finished_thread(self):
        self.stateToolTip.hide()
        InfoBar.success('成功', '合并成功', duration=3000, parent=self)

    def resizeEvent(self, event: QResizeEvent):
        self.stateToolTip.move(event.size().width() - self.stateToolTip.width() - 20, 10)
        super().resizeEvent(event)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = UnionQueryView()
    win.resize(1000, 700)
    win.show()
    sys.exit(app.exec())
